package com.tt.service.impl;

import com.tt.common.Const.TtConstans;
import com.tt.common.enums.DateEnum;
import com.tt.common.exception.TtException;
import com.tt.common.ftp.FtpUtils;
import com.tt.common.page.TtResult;
import com.tt.common.param.FtpPo;
import com.tt.common.util.DateUtil;
import com.tt.common.util.EnumUtil;
import com.tt.common.util.IDUtils;
import com.tt.service.IFileUploadService;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 青青
 */
@Service
public class FileUploadServiceImpl implements IFileUploadService
{

    @Override
    public TtResult uploadFile(FtpPo ftpPo) throws Exception
    {
        try
        {
            /*
             * 生成新的文件名
             */

            String fileName = ftpPo.getFileName();
            InputStream inputStream = ftpPo.getInputStream();
            Integer ftp_port = ftpPo.getFTP_PORT();
            String ftp_username = ftpPo.getFTP_USERNAME();
            String ftppassrd = ftpPo.getFTPPASSRD();
            String ftpHost = ftpPo.getFTPHost();
            String image_base_home = ftpPo.getIMAGE_BASE_home();
            String image_base_url = ftpPo.getIMAGE_BASE_URL();

            //生成新的文件名
            String newName = IDUtils.genImageName();
            newName = newName+fileName.substring(fileName.lastIndexOf("."));

            DateEnum yMdHms = DateEnum.yyyyMMdd;
            String type = DateEnum.getValue(yMdHms.name());

            //图片上传
            String imagePath = DateUtil.getDateStr(type);

            boolean result =  FtpUtils.uploadFile(ftpHost, ftp_port, ftp_username, ftppassrd,image_base_home,imagePath, newName, inputStream);

            if(result)
            {
                return TtResult.ok(TtConstans.http+image_base_url+imagePath+"/"+newName);
            }
            throw new TtException("文件上传失败");
        } catch (Exception e)
        {
            throw new TtException("文件上传发送异常");
        }
    }
}
